<?php

namespace app\api\controller;

use app\api\model\Gold;
use app\common\controller\Api;
use app\common\model\order\Pay;
use app\common\model\user\Withdraw;
use think\Db;
use think\Exception;

class Recharge extends Api
{
    protected $noNeedLogin = ["mini_pay_notify"];
    protected $noNeedRight = "*";

    public function list()
    {
        $this->success("列表", Gold::list());
    }

    public function pay()
    {
        $params = $this->request->param();
        $params['user_id'] = $this->auth->id;

        $result = Pay::pay($params);
        $app = \app\common\library\Pay::app();
        $pay = $app->order->unify([
            'body' => '金币充值_' . $result->id,
            'out_trade_no' => $result->order_sn,
            'total_fee' => $result->price * 100,
            'trade_type' => 'JSAPI',
            'openid' => $this->auth->openid
        ]);
        if ($pay['return_code'] === 'SUCCESS') {
            if ($pay['result_code'] === 'SUCCESS') {
                $data = ['order_id' => $result->id, 'payment' => $app->jssdk->bridgeConfig($pay['prepay_id'], false)];
                $this->success("支付信息", $data);
            }
        }
        Pay::pay_error($result->id, ["status" => 2, "err_code" => $pay['err_code'], "err_code_des" => $pay['err_code_des']]);
        $this->error("请求支付失败", $pay);
    }

    public function mini_pay_notify()
    {
        $app = \app\common\library\Pay::app();
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = Pay::where(['order_sn' => $message['out_trade_no']])->find();
            if (!$order || $order['status'] != 0) {
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message["result_code"] === 'SUCCESS') {
                    Pay::update(['status' => 1, 'pay_time' => time()], ['order_sn' => $message['out_trade_no']]);
                    \app\common\model\User::money($order['money'], $order['user_id'], 0, $order['id']);
                } elseif ($message["result_code"] === 'FAIL') {
                    Pay::pay_error(["err_code" => $message['result_code'], "err_code_des" => $message['return_msg'], 'status' => 2], ['order_sn' => $message['out_trade_no']]);
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });

        $response->send();
    }

    public function withdraw()
    {
        $params = $this->request->param();
        $params['user_id'] = $this->auth->id;
        if ($this->auth->group_id != 1) {
            $this->error("当前身份有误");
        }
        if ($this->auth->real_auth != 1) {
            $this->error('请先实名认证');
        }
        if(!is_numeric($params['money'])){
            $this->error("请输入数字");
        }

        if ($params['money'] > $this->auth->money) {
            $this->error("当前余额不足");
        }
        try {
            $result = Withdraw::operate($params);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        if ($result) {
            $this->success("申请提现成功", $result);
        } else {
            $this->error("申请有误,请稍后再试");
        }
    }

    public function withdraw_log()
    {
        $user_id = $this->auth->id;
        $pageSize = $this->request->post('pagesize');
        $data = Db::name('user_withdraw')->where('user_id', $user_id)->order('updatetime desc')->paginate($pageSize)->each(function ($v) {
            $v['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
            return $v;
        });
        $this->success('成功', $data);
    }
}